package org.m8.auth.handler.mobile;

import cn.hutool.core.util.RandomUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.m8.auth.handler.AbstractAuthLoginHandler;
import org.m8.auth.handler.AuthLoginHandlerRegistry;
import org.m8.auth.controller.vo.AuthLoginRespVO;
import org.m8.user.model.User;
import org.m8.user.model.UserService;
import org.m8.util.JsonUtil;
import org.m8.util.StatusEnum;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

import static org.m8.util.exception.ServiceExceptionUtil.exception;
import static org.m8.util.exception.emnus.GlobalErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS;
import static org.m8.util.exception.emnus.GlobalErrorCodeConstants.AUTH_MOBILE_NOT_EXISTS;

/**
 * 手机短信验证码登录
 *
 * @author yidanjun
 * @date 2024/9/7
 **/
@Service
@Slf4j
public class MobileAuthLoginHandler extends AbstractAuthLoginHandler {

    private static final String AUTH_LOGIN_TYPE = "mobile";

    @Resource
    private UserService userService;
    @Override
    protected void init() {
        AuthLoginHandlerRegistry.getInstance().register(AUTH_LOGIN_TYPE, this);
    }

    @Override
    public < R extends AuthLoginRespVO> R login(Map<String, Object> req) {
        MobileAuthLoginReqVO mobileAuthLoginReqVO = JsonUtil.parse(req, MobileAuthLoginReqVO.class);
        User user = userService.getByMobile(mobileAuthLoginReqVO.getMobile());
        if (user == null){
            throw exception(AUTH_MOBILE_NOT_EXISTS);
        }

        if (!Objects.equals(user.getStatus(), StatusEnum.VALID.getValue())){
            log.error("用户状态异常，mobile: {}", mobileAuthLoginReqVO.getMobile());
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }

         // todo 校验验证码是否正确
        log.info("手机短信验证码登录，mobile: {}， smsCode: {}", mobileAuthLoginReqVO.getMobile(), mobileAuthLoginReqVO.getSmsCode());
        return (R) createTokenAfterLoginSuccess(user);
    }

    public void sendLoginSmsCode(String mobile) {
        User user = userService.getByMobile(mobile);
        if (user == null){
            throw exception(AUTH_MOBILE_NOT_EXISTS);
        }
        if (!Objects.equals(user.getStatus(), StatusEnum.VALID.getValue())){
            log.error("用户状态异常，mobile: {}", mobile);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }

        String smsCode = RandomUtil.randomNumbers(6);
        log.info("发送短信验证码：{}", smsCode);

        // todo
    }


}
